/**
 * 创建测试用户
 */
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'Lycc.2025',
  database: 'fun_english_db'
};

async function createTestUser() {
  let connection;
  
  try {
    console.log('📡 正在连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功\n');
    
    // 检查用户是否已存在
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE username = ?',
      ['nice']
    );
    
    if (existingUsers.length > 0) {
      console.log('⚠️  测试用户 "nice" 已存在');
      console.log('🔄 正在更新密码...');
      
      const hashedPassword = await bcrypt.hash('nice', 10);
      await connection.execute(
        'UPDATE users SET password = ? WHERE username = ?',
        [hashedPassword, 'nice']
      );
      
      console.log('✅ 密码已更新\n');
    } else {
      console.log('🆕 正在创建测试用户 "nice"...');
      
      const hashedPassword = await bcrypt.hash('nice', 10);
      
      const [result] = await connection.execute(
        `INSERT INTO users (username, password, school, grade, avatar, stars) 
         VALUES (?, ?, ?, ?, ?, ?)`,
        ['nice', hashedPassword, '测试小学', '三上', 'avatar1', 0]
      );
      
      const userId = result.insertId;
      
      // 创建默认宠物
      await connection.execute(
        `INSERT INTO pets (user_id, pet_type, pet_name, level, exp, hunger, happiness, health)
         VALUES (?, ?, ?, 1, 0, 100, 100, 100)`,
        [userId, 'dragon', '小龙']
      );
      
      console.log('✅ 测试用户创建成功\n');
    }
    
    console.log('=================================');
    console.log('🎉 测试用户配置完成！');
    console.log('=================================');
    console.log('用户名: nice');
    console.log('密码: nice');
    console.log('学校: 测试小学');
    console.log('年级: 三上');
    console.log('=================================\n');
    
  } catch (error) {
    console.error('❌ 错误:', error.message);
    process.exit(1);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

createTestUser();

